package com.hly.musicbackground.model.boots.rest;

import com.hly.musicbackground.Utils.RequestContextUtils;
import com.hly.musicbackground.Utils.ThreadPoolUtils;
import com.hly.musicbackground.model.boots.VO.FictionDetailVO;
import com.hly.musicbackground.model.boots.VO.FictionListVO;
import com.hly.musicbackground.model.boots.VO.FictionQueryDataVO;
import com.hly.musicbackground.model.boots.params.FictionQueryParams;
import com.hly.musicbackground.model.boots.service.FictionChapterService;
import com.hly.musicbackground.model.boots.service.FictionService;
import com.hly.musicbackground.model.boots.service.impl.FictionServiceImpl;
import com.hly.musicbackground.result.Code;
import com.hly.musicbackground.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 小说
 * */
@RestController
@RequestMapping("/api/fiction")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags = "小说")
public class FictionController {

    private final FictionService fictionService;
    private final FictionChapterService fictionChapterService;

    private static boolean isTimeUpdate = false;

    /**
     * 获取小说详情
     * @param id 小说id
     * */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "获取小说详情")
    public Result<FictionDetailVO> detail(@PathVariable("id") int id){
        int userId = RequestContextUtils.getUser().getUserId();
        return Result.ok(fictionService.getFictionDetail(id, userId));
    }

    /**
     * 小说列表
     * @param params 筛选
     * */
    @GetMapping("/list")
    @ApiOperation(value = "小说列表")
    public Result<FictionListVO> fictionQueryList(FictionQueryParams params){
        return Result.ok(fictionService.fictionQueryList(params));
    }

    /**
     * 检查用户书架中的小说是否更新【即将淘汰】
     * */
    @PostMapping("/checkNew")
    @ApiOperation(value = "检查用户书架中的小说是否更新【即将淘汰,不推荐使用】")
    public Result<Boolean> checkNew(){
        int userId = RequestContextUtils.getUser().getUserId();
        return Result.ok(fictionService.UserBookshelfInspectUpdateFiction(userId));
    }

    /**
     * 获取小说筛选条件
     * */
    @GetMapping("/queryData")
    @ApiOperation(value = "获取小说筛选条件")
    public Result<List<FictionQueryDataVO>> fictionQueryData(){
        return Result.ok(fictionService.fictionQueryData());
    }

    /**
     * 爬取小说
     * */
    @GetMapping("/paqu/{id}")
    @ApiOperation(value = "禁止调用")
    public Result paqu(@PathVariable("id") int id){
        if (isTimeUpdate){
            Code.BUSINESS_ERR("正在爬取");
        }
        ThreadPoolUtils.start(() -> {
            fictionService.paqu(id);
        });
        isTimeUpdate = true;
        return Result.ok();
    }

}
